<template>
  <!-- 入场视频 -->
  <div class="video-container" v-if="showIntroVideo" @click="skipIntroVideo">
    <video 
      ref="introVideo" 
      class="intro-video" 
      autoplay 
      muted 
      @ended="introVideoEnded">
      <source src="../assets/video/intro_pc.mp4" type="video/mp4">
    </video>
    <div class="skip-button">点击跳过</div>
  </div>

  <!-- 循环背景视频 -->
  <div class="loop-video-container" v-show="!showIntroVideo">
    <video 
      ref="loopVideo" 
      class="loop-video" 
      autoplay 
      muted 
      loop>
      <source src="../assets/video/loop_pc.mp4" type="video/mp4">
    </video>
  </div>

  <!-- 登录界面 -->
  <transition name="fade" appear>
    <div class="login-container" v-show="!showIntroVideo">
      <div class="login-layout">
        <div class="left-panel">
          <h1>嗨<span class="wave">👋</span> 朋友</h1>
          <p style="margin: 2px 0;">是新朋友吗？</p>
          <p>欢迎点击下方注册加入我们</p>
          <el-button class="sign-up-btn" @click="navigateToRegister">注册</el-button>
        </div>
        <div class="right-panel">

          <div class="title" style="font-size: 32px; font-weight: bold; color: #333;">登入</div>
          <div class="typewriter-container">
            <span class="typewriter-text">{{ currentText }}</span>
            <span class="cursor" :class="{ 'blink': !isTyping }">|</span>
          </div>
          <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form">
            <el-form-item prop="username">
              <el-input v-model="loginForm.username" placeholder="用户名" :prefix-icon="User" @keyup.enter="handleLogin"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model="loginForm.password" type="password" placeholder="密码" :prefix-icon="Lock" show-password @keyup.enter="handleLogin"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleLogin" :loading="loading" class="login-button">登录</el-button>
            </el-form-item>
            <div class="admin-login-link">
              <a @click="navigateToAdminLogin">点击此处登录管理员系统</a>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import request from '../utils/request'
import { el } from 'element-plus/es/locales.mjs'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)
const showIntroVideo = ref(true)
const introVideo = ref(null)
const loopVideo = ref(null)

// 打字机效果变量
const loginTips = [
  '🎮 玩家请输入通关密令，解锁新副本！',
  '🔮 神秘入口：正确咒语将召唤你的专属社团',
  '📚 输入你的专属暗号，故事从这里开始',
  '🎨 调色盘已就位，请用密码点亮你的色彩',
  '🎵 登录成功后将播放属于你的社团BGM',
  '🛡️ 勇者啊，输入密令开启你的荣耀征程！',
  '👀 偷偷告诉你：社长也在输入密码中...',
  '🎸 Login或Rock in，你都是最靓的仔'
]
const currentText = ref('')
const currentTipIndex = ref(0)
const isTyping = ref(true)
let typingTimer = null

const typeText = () => {
  const currentTip = loginTips[currentTipIndex.value]
  const targetLength = isTyping.value ? currentTip.length : 0
  
  if (isTyping.value && currentText.value.length < targetLength) {
    // 正在输入中
    currentText.value = currentTip.substring(0, currentText.value.length + 1)
    typingTimer = setTimeout(typeText, 50)
  } else if (!isTyping.value && currentText.value.length > 0) {
    // 正在删除中
    currentText.value = currentText.value.substring(0, currentText.value.length - 1)
    typingTimer = setTimeout(typeText, 30)
  } else if (isTyping.value) {
    // 输入完成，等待一会后开始删除
    isTyping.value = false
    typingTimer = setTimeout(typeText, 2000)
  } else {
    // 删除完成，切换到下一条提示
    currentTipIndex.value = (currentTipIndex.value + 1) % loginTips.length
    isTyping.value = true
    typingTimer = setTimeout(typeText, 500)
  }
}

const loginForm = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const introVideoEnded = () => {
  // 入场视频结束后，隐藏入场视频，显示循环视频和登录表单
  showIntroVideo.value = false
  
  // 确保循环视频开始播放
  if (loopVideo.value) {
    loopVideo.value.play()
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    const res = await request({
      url: '/auth/login',
      method: 'post',
      data: loginForm
    })
    localStorage.setItem('token', res.data)
    if (!res.success){
      ElMessage.error(res.message)
      return
    }

    if (res.success) {
      const userInfo = await request({
        url: '/auth/info',
        method: 'get'
      })
      
      if (userInfo.data.role !== 0 && userInfo.data.role !== 1) {
        throw new Error('用户名或密码错误')
      }
      
      localStorage.setItem('token', res.data)
      localStorage.setItem('username', loginForm.username)
      localStorage.setItem('userRole', userInfo.data.role)
      localStorage.setItem('userId', userInfo.data.id)
      ElMessage.success('登录成功')
      // router.push('/home')
      // 强制刷新页面 解决 router.push 导致页面不刷新的问题
      window.location.href = '/home'
    }
  } catch (error) {
    ElMessage.error(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const navigateToRegister = () => {
  // 强制刷新页面 解决 router.push 导致页面不刷新的问题
  window.location.href = '/register'
  
  // （备选）：使用 router.push 但添加强制重载标记
  // router.push({
  //   path: '/register',
  //   query: { _t: Date.now() }
  // })
}

const navigateToAdminLogin = () => {
  // 强制刷新页面 解决 router.push 导致页面不刷新的问题
  window.location.href = '/admin/login'
  
  // （备选）：使用 router.push 但添加强制重载标记
  // router.push({
  //   path: '/admin/login',
  //   query: { _t: Date.now() }
  // })
}

const skipIntroVideo = () => {
  showIntroVideo.value = false
  if (loopVideo.value) {
    loopVideo.value.play()
  }
}

// 组件挂载时执行
onMounted(() => {
  // 启动打字机效果
  typeText()
  
  // 如果用户已经登录过，可以跳过视频
  if (localStorage.getItem('token')) {
    showIntroVideo.value = false
    // 确保循环视频开始播放
    if (loopVideo.value) {
      loopVideo.value.play()
    }
  }
})

// 组件卸载时清除定时器
onUnmounted(() => {
  if (typingTimer) {
    clearTimeout(typingTimer)
  }
})

// 添加这个钩子来处理组件被激活时的逻辑
onActivated(() => {
  if (loopVideo.value && !showIntroVideo.value) {
    loopVideo.value.play()
  }
})
</script>

<style scoped>
.video-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #000;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  cursor: pointer;
}

.intro-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loop-video-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;  /* 放在登录表单后面 */
  overflow: hidden;
}

.loop-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 视频淡出效果 */
.fade-leave-active {
  transition: opacity 1s;
}

.fade-leave-to {
  opacity: 0;
}

.typewriter-container {
  height: 40px;
  margin: 10px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.typewriter-text {
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  height: 20px;
  display: inline-block;
}

.cursor {
  display: inline-block;
  margin-left: 2px;
  font-weight: bold;
  color: #333;
}

.cursor.blink {
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

.admin-login-link {
  text-align: center;
  margin-top: 15px;
  font-size: 14px;
}

.admin-login-link a {
  color: #4776E6;
  text-decoration: underline;
  cursor: pointer;
  transition: color 0.3s ease;
}

.admin-login-link a:hover {
  color: #8E54E9;
}

:root {
  --primary-color: #409EFF;
  --background-gradient: #f5f7fa;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html, body {
  overflow: auto;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: var(--background-gradient);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  margin:0;
  padding:0;
  border:0
}

.login-container {
  height: 100vh;
  width: 100vw;
  display: grid;
  place-items: center;
  overflow: hidden;
  margin: 0;
  padding: 0;
  position: relative;
}

.login-container::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4); /* 半透明黑色背景，让视频变暗 */
  z-index: -1;
}

.login-layout {
  width: 100%;
  max-width: 970px;
  height: 600px;
  display: flex;
  border-radius: 24px;
  box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
  overflow: hidden;
  margin: auto;
  z-index: 1;
  background: rgba(255, 255, 255, 0.95); /* 稍微透明的白色背景 */
}

.left-panel {
  flex: 0.4;
  background: linear-gradient(to right, #effd47, #e58881);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 40px;
}

.left-panel h1 {
  font-size: 36px;
  margin-bottom: 20px;
}

.left-panel p {
  font-size: 16px;
  line-height: 1.5;
  margin-bottom: 30px;
}

.sign-up-btn {
  background: transparent;
  border: 1px solid white;
  color: white;
  padding: 12px 45px;
  font-size: 16px;
  border-radius: 20px;
  text-transform: uppercase;
  transition: transform 0.3s ease;
}

.sign-up-btn:hover {
  transform: scale(1.05);
  background: rgba(255, 255, 255, 0.1);
}

.right-panel {
  flex: 1.2;
  background: white;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.right-panel h2 {
  font-size: 32px;
  margin-bottom: 20px;
  color: #333;
}

.social-icons {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.social-icon {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  transition: all 0.3s ease;
}

.social-icon:hover {
  background: #f5f5f5;
  transform: translateY(-2px);
}

.subtitle {
  color: #666;
  margin-bottom: 30px;
}

.login-form {
  width: 100%;
  max-width: 380px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  background: linear-gradient(to right, #4776E6, #8E54E9);
  border: none;
  border-radius: 20px;
  color: white;
  text-transform: uppercase;
  margin-top: 20px;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 7px 14px rgba(71, 118, 230, 0.3);
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 表单元素动画 */
.login-form .el-form-item {
  transition: transform 0.3s ease;
}

.login-form .el-form-item:hover {
  transform: translateX(5px);
}

.social-icon {
  animation: bounce 1s ease infinite;
}

@keyframes bounce {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
}

:deep(.el-input__wrapper) {
  background: #f5f5f5;
  border-radius: 20px;
  box-shadow: none !important;
  padding: 8px 15px;
}

:deep(.el-input__wrapper.is-focus) {
  background: white;
  box-shadow: 0 0 0 1px #4776E6 inset !important;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__inner) {
  height: 40px;
}

:deep(.el-input__prefix) {
  color: #666;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.wave {
  display: inline-block;
  animation: wave-animation 2.5s infinite;
  transform-origin: 70% 70%;
}

@keyframes wave-animation {
  0% { transform: rotate(0deg); }
  10% { transform: rotate(14deg); }
  20% { transform: rotate(-8deg); }
  30% { transform: rotate(14deg); }
  40% { transform: rotate(-4deg); }
  50% { transform: rotate(10deg); }
  60% { transform: rotate(0deg); }
  100% { transform: rotate(0deg); }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .login-layout {
    flex-direction: column;
    height: auto;
    max-width: 90%;
    margin: 20px auto;
  }

  .left-panel {
    flex: none;
    padding: 30px;
    border-radius: 24px 24px 0 0;
  }

  .left-panel h1 {
    font-size: 28px;
  }

  .left-panel p {
    font-size: 14px;
    margin-bottom: 15px;
  }

  .right-panel {
    flex: none;
    padding: 20px;
    border-radius: 0 0 24px 24px;
  }

  .right-panel .title {
    font-size: 24px;
  }

  .typewriter-text {
    font-size: 14px;
  }

  .login-form {
    max-width: 100%;
  }

  .login-button {
    height: 40px;
    font-size: 14px;
  }

  :deep(.el-input__inner) {
    height: 36px;
  }

  .sign-up-btn {
    padding: 10px 35px;
    font-size: 14px;
  }

  .video-container,
  .loop-video-container {
    position: fixed;
    width: 100%;
    height: 100%;
  }

  .intro-video,
  .loop-video {
    object-fit: cover;
  }
}

/* 小屏幕手机适配 */
@media screen and (max-width: 375px) {
  .login-layout {
    max-width: 95%;
  }

  .left-panel h1 {
    font-size: 24px;
  }

  .left-panel p {
    font-size: 12px;
  }

  .right-panel .title {
    font-size: 20px;
  }

  .typewriter-text {
    font-size: 12px;
  }
}

/* 横屏适配 */
@media screen and (max-height: 500px) and (orientation: landscape) {
  .login-layout {
    height: 90vh;
    margin: 5vh auto;
  }

  .left-panel,
  .right-panel {
    padding: 20px;
  }

  .left-panel h1 {
    font-size: 24px;
    margin-bottom: 10px;
  }

  .left-panel p {
    margin-bottom: 10px;
  }

  .login-form {
    max-width: 100%;
  }
}

.skip-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.skip-button:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: scale(1.05);
}
</style>